const express = require("express");
const ejs = require("ejs");
const path = require("path");
const fs = require("fs/promises");
const app = express();

// 模板引擎
app.use(function (req, res, next) {
  res.render = async function (filename, data) {
    let ext = app.get("view engine");
    let view = app.get("views");
    const tmplUrl = path.join(view, filename + "." + ext);
    let tmplStr = await fs.readFile(tmplUrl, "utf8");
    let head = 'let str = "";\nwith(obj){\n';
    let content = "str += `\n";
    tmplStr = tmplStr.replace(/<%=(.*?)%>/g, function () {
      return "${" + arguments[1] + "}";
    });
    // 表达式处理
    tmplStr = tmplStr.replace(/<%(.+?)%>/g, function () {
      return "`\n" + arguments[1] + "\nstr += `";
    });
    content += tmplStr;
    let foot = `\` \n}\n
    return str`;
    let tmpl = new Function("obj", head + content + foot)(data);
    res.end(tmpl);
  };
  res.send = function (data) {
    if (typeof data === "object") {
      res.setHeader("Content-Type", "application/json;charset=utf-8");
      res.end(JSON.stringify(data));
    }
  };
  res.sendFile = async function (path) {
    let filecontent = await fs.readFile(path, "utf8");
    res.end(filecontent);
  };
  next();
});

app.use(express.static(__dirname)); // 内置了 静态服务中间件
// 参数配置
app.engine("html", ejs.__express); // 配置参数
app.set("view engine", "html");
app.set("views", path.resolve(__dirname, "view"));

// 路由的视线
app.get("/", function (req, res) {
  res.render("index", { name: "jw", arr: [1, 2, 3] });
});
app.get("/getUser", function (req, res) {
  // res.send({ id: 1 });
  res.sendFile(path.resolve(__dirname, "index.js"));
});
app.listen(3000, function (req, res) {
  console.log("server start 3000");
});
